package com.founder.android.http;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Date;

import org.apache.http.HttpEntity;

/**
 * 下载文件的HTTP请求包装类
 * @author chen_weihua
 *
 */
public class FileCallbackWapper extends CallbackWrapper {
	
	private File file;
	
	private static final int BUFFER = 1024;

	public FileCallbackWapper(ResponseListener callbackActivity) {
		super(callbackActivity);
	}
	
	public void setFile(File file) {
		this.file= file;
	}

	@Override
	protected void onResponseSuccess() {
		callbackActivity.onResponseSuccess(response, file);
	}
	
	@Override
	protected void setResult() throws Exception {
		HttpEntity entity = response.getEntity();
		InputStream in = entity.getContent();
		boolean success = false;
		try {
			//创建临时文件
			File parent = new File(file.getParent());
			if (!parent.exists()) {
				parent.mkdir();
			}
			String tempPath = file.getParent() + File.separator + "temp_" + new Date().getTime();
			File tempFile = new File(tempPath);
			int index = 1;
			while (tempFile.exists()) {
				String newTempPath = tempPath  + index;
				tempFile = new File(newTempPath);
				index++;
			}
			//tempFile.createNewFile();
			//FileOutputStream out = new FileOutputStream(tempFile);
	        if (charset != null) {
	        	//使用字符流,防止乱码
	        	OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(tempFile));
	        	try {
	        		int len = 0;
		        	char[] b = new char[BUFFER];
		        	InputStreamReader reader = new InputStreamReader(in, charset);
					while ((len=reader.read(b))!= -1) {  
			            out.write(b,0,len);  
			        }
					success = true;
	        	} finally {
		        	out.close();
		        	if (success) {
		        		copyFile(tempFile, file);
		        	}
		        	tempFile.delete();
	        	}
			} else {
				FileOutputStream out = new FileOutputStream(tempFile);
				try {
					int len = 0;
					byte[] b = new byte[BUFFER];
			        while ((len=in.read(b))!= -1) {  
			            out.write(b,0,len);  
			        }
			        success = true;
				} finally {
		        	out.close();
		        	if (success) {
		        		copyFile(tempFile, file);
		        	}
		        	tempFile.delete();
	        	}
			}
		} finally {
			in.close();
		}
		
	}
	
	private void copyFile(File src, File dist) throws Exception {
		FileInputStream in = new FileInputStream(src);
		try {
			FileOutputStream out = new FileOutputStream(dist);
			try {
		        byte[] b = new byte[BUFFER];  
		        int len = 0;
		        while((len=in.read(b))!= -1) {  
		            out.write(b,0,len);  
		        }
			} finally {
				out.close();
			}
		} finally {
			in.close();
		}
	}

}
